﻿using Microsoft.Toolkit.Mvvm.Messaging;
using SimpleBoard.DependencyInjection;
using SimpleBoard.Designer.Controls;
using SimpleBoard.Designer.Messages;
using SimpleBoard.Designer.Services;
using SimpleBoard.Designer.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SimpleBoard.Designer.Pages
{
    /// <summary>
    /// PropertyPanel.xaml 的交互逻辑
    /// </summary>
    [InjectAs(InjectionType.Transient)]
    public partial class PropertyPanel : Page, IRecipient<ActiveElementChangedMessage>
    {
        public PropertyPanel(PropertyPanelViewModel viewModel, ControllerService controllerService)
        {
            InitializeComponent();
            this.DataContext = viewModel;
            this.viewModel = viewModel;
            this.controllerService = controllerService;
            WeakReferenceMessenger.Default.Register<ActiveElementChangedMessage>(this);
        }

        ~PropertyPanel()
        {
            WeakReferenceMessenger.Default.Unregister<ActiveElementChangedMessage>(this);
        }

        private readonly PropertyPanelViewModel viewModel;
        private readonly ControllerService controllerService;

        public void Receive(ActiveElementChangedMessage message)
        {
            if (message.Element is null)
            {
                return;
            }
            this.viewModel.TargetElement = message.Element;

            this.DynamicPropertyPanel.Children.Clear();
            var controllerInfo = controllerService.GetControllerInfo(message.Element);
            foreach (var prop in controllerInfo.Properties)
            {
                var setter = App.AutoWired<StringSetter>();
                setter.Title = prop.Title;
                setter.TargetElement = message.Element;
                setter.TargetProperty = prop;
                this.DynamicPropertyPanel.Children.Add(setter);
            }

            var position = controllerService.GetPosition(message.Element);
            var size = controllerService.GetSize(message.Element);

            this.viewModel.ElementLeft = (int)position.X;
            this.viewModel.ElementTop = (int)position.Y;
            this.viewModel.ElementWidth = (int)size.Width;
            this.viewModel.ElementHeight = (int)size.Height;
            this.viewModel.ElementType = controllerInfo.Title;
        }
    }
}
